import 'package:bluetooth_flutter_plugin/bluetooth_flutter_plugin.dart';
import 'package:bluetooth_flutter_plugin_example/dialog.dart';
import 'package:flutter/material.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:fluttertoast/fluttertoast.dart';

class BluetoothAdapterLorin extends BluetoothAdapterBase {
  @override
  Guid get notifyCharacteristicUuid =>
      Guid('6e400003-b5a3-f393-e0a9-e50e24dcca9e');

  @override
  Guid get notifyServiceUuid => Guid('6e400001-b5a3-f393-e0a9-e50e24dcca9e');

  @override
  Guid get writeCharacteristicUuid =>
      Guid('6e400002-b5a3-f393-e0a9-e50e24dcca9e');

  @override
  Guid get writeServiceUuid => Guid('6e400001-b5a3-f393-e0a9-e50e24dcca9e');
}

class LorinSendHandler extends BluetoothSendHandler {
  @override
  bool get supportsConcurrentRequests => true;

  @override
  int get concurrentRequestsMaxLength => 256;

  @override
  String getRequestMsgId(List<int> requestData) {
    return "";
  }

  @override
  String getResponseMsgId(List<int> responseData) {
    return "";
  }
}

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final BluetoothHelper _bluetoothHelper = BluetoothHelper(
    BluetoothAdapterLorin(),
    LorinSendHandler(),
  );

  @override
  void initState() {
    super.initState();

    _bluetoothHelper.bluetoothConnectState.listen((event) {
      switch (event) {
        case BluetoothConnectState.unavailable:
          Fluttertoast.showToast(msg: "不可用");
          break;
        case BluetoothConnectState.idle:
          break;
        case BluetoothConnectState.isScanning:
          break;
        case BluetoothConnectState.connected:
          LxLoading.dismiss(context);
          Fluttertoast.showToast(msg: "连接成功");
          break;
        case BluetoothConnectState.connecting:
          LxLoading.show(context);
          break;
        case BluetoothConnectState.disconnected:
          LxLoading.dismiss(context);
          Fluttertoast.showToast(msg: "连接断开");
          break;
      }
    });
  }

  List<ScanResult> scanResults = [];

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Bluetooth Plugin Demo'),
        ),
        body: Column(
          children: [
            Expanded(
              child: ListView.builder(
                itemCount: scanResults.length,
                itemBuilder: (context, index) {
                  ScanResult result = scanResults[index];
                  return InkWell(
                    onTap: () async {
                      LxLoading.show(context);
                      _bluetoothHelper.connect(result.device).whenComplete(() {
                        LxLoading.dismiss(context);
                        Fluttertoast.showToast(msg: "连接成功");
                      });
                    },
                    child: ListTile(
                      title: Text(result.advertisementData.advName),
                      subtitle: Text(result.device.remoteId.toString()),
                    ),
                  );
                },
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(16.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  ElevatedButton(
                    onPressed: () async {
                      await _bluetoothHelper.startScan(
                        callbackScanResults: (devices) {
                          setState(() {
                            debugPrint("【$runtimeType】result: $devices");
                            scanResults = devices;
                          });
                        },
                      );
                    },
                    child: const Text('开始扫描'),
                  ),
                  ElevatedButton(
                    onPressed: () async {
                      await _bluetoothHelper.stopScan();
                    },
                    child: const Text('停止扫描'),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
